package com.fordmotor.api;

import com.fordmotor.config.BaseConfig;
import com.fordmotor.config.GitHubConfig;
import com.fordmotor.pojo.AccessTokenVO;
import com.fordmotor.pojo.GitUser;
import com.fordmotor.pojo.WxchatUser;
import com.fordmotor.service.GitHubService;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.UUID;

import static com.fordmotor.cache.EhCache.cacheManager;
@Controller
public class GitHubAPI {
@Autowired
    private GitHubService gitHubService;

    @PostMapping(value = "/login")
    public String wxKfLoginPage(HttpServletRequest request) throws Exception {
        // 防止csrf攻击（跨站请求伪造攻击）
        String state = UUID.randomUUID().toString().replaceAll("-", "");
        HttpSession session = request.getSession();
        //存入session
        session.setAttribute("wechat-kf-state",state);
        //普通微信三方地址
        String url = GitHubConfig.getAuthorize() +
                "appid="+ GitHubConfig.getClientId() +
                "&redirect_uri="+GitHubConfig.getCallback()+
                "&response_type=code" +
                "&scope=snsapi_base" +
                "&state="+state;
        return "redirect:"+url;
    }

    @RequestMapping("/callback")
    public String callback(@RequestParam(name = "code") String code,
                           @RequestParam(name = "state") String state,
                           HttpServletRequest request,HttpServletResponse response) {
        //通过一个DTO对象封装,接收的code state
        AccessTokenVO accessTokenVO = new AccessTokenVO();
        accessTokenVO.setCode(code);
        accessTokenVO.setClientId(request.getParameter("clientId"));
        accessTokenVO.setClientSecret(request.getParameter("clientSecret"));
        accessTokenVO.setState(state);
        accessTokenVO.setRedirectUrl(request.getParameter("redirectUrl"));
        //得到github传回来的数据 code + Client Secret+Client id来获取token
        String accessToken = gitHubService.getAccessToken(accessTokenVO);
        //通过解析封装成一个对象
        GitUser githubUser = gitHubService.getUserInfo(accessToken);
        Ehcache cache = cacheManager.getCache("member");
        Element e = cache.getQuiet(githubUser.getUserid());
        if (e == null){
            Element element = new Element(githubUser.getUserid(),githubUser);
            cache.put(element);
        }
        return "redirect:/home";
    }
}
